import router, { constantRoutes, dynamicRoutes } from '@/router';
import { reqQueryMenuTree } from '@/views/Custom/SystemSettingsMng/MenuMng/api/MenuMngApi';
import Layout from '@/layout/index';

const permission = {
  // namespaced: true,
  state: {
    routes: [],
    addRoutes: [],
    defaultRoutes: [],
    topbarRouters: [],
    sidebarRouters: [],
  },
  mutations: {
    SET_ROUTES: (state, routes) => {
      state.addRoutes = routes;
      state.routes = constantRoutes.concat(routes);
    },
    SET_DEFAULT_ROUTES: (state, routes) => {
      state.defaultRoutes = constantRoutes.concat(routes);
    },
    SET_TOPBAR_ROUTES: (state, routes) => {
      state.topbarRouters = routes;
    },
    SET_SIDEBAR_ROUTERS: (state, routes) => {
      state.sidebarRouters = routes;
    },
  },
  actions: {
    // 生成路由
    GenerateRoutes({ commit }) {
      return new Promise((resolve) => {
        // 向后端请求路由数据
        reqQueryMenuTree().then((res) => {
          if (!res.data || !res.data.menuTree) {
            commit('SET_SIDEBAR_ROUTERS', constantRoutes);
            resolve(constantRoutes);
            return;
          }
          const sdata = res.data.menuTree;
          const rdata = res.data.menuTree;
          const sidebarRoutes = convertMenuToRoutes(sdata);
          const rewriteRoutes = convertMenuToRoutes(rdata);
          // const asyncRoutes = filterDynamicRoutes(dynamicRoutes);
          // 404 页面
          rewriteRoutes.push(
            {
              path: '/404',
              component: () => import('@/views/404'),
            },
            { path: '*', redirect: '/404', hidden: true }
          );
          // 404 页面
          sidebarRoutes.push(
            {
              path: '/404',
              component: () => import('@/views/404'),
            },
            { path: '*', redirect: '/404', hidden: true }
          );
          // router.addRoutes(asyncRoutes);
          commit('SET_ROUTES', rewriteRoutes);
          commit('SET_SIDEBAR_ROUTERS', constantRoutes.concat(sidebarRoutes));
          commit('SET_DEFAULT_ROUTES', sidebarRoutes);
          commit('SET_TOPBAR_ROUTES', sidebarRoutes);
          resolve(rewriteRoutes);
        });
      });
    },
    // 获取登录用户拥有的角色与权限
  },
};

// 动态路由
function convertMenuToRoutes(menus) {
  const routes = [];
  menus.forEach((menu) => {
    const route = {
      path: menu.path,
      name: menu.name,
      redirect: menu.redirect,
      alwaysShow: menu.alwaysShow == 1 ? true : false,
      hidden: menu.hasHidden == 1 ? true : false,
      meta: { title: menu.title, icon: menu.icon },
    };
    if (menu['component'] === 'Layout') route.component = Layout;
    else {
      route.component = loadView(menu.component);
    }
    // 是否有 props 属性
    if (menu.hasProps) {
      switch (menu.title) {
        case '专业列表':
          route.props = ({ params: { departmentId } }) => ({ departmentId });
          break;
        case '编辑学员':
          route.props = ({ params: { editStudentInfo, depAndMajorMenu } }) => ({
            editStudentInfo,
            depAndMajorMenu,
          });
          break;
        // case '新增学员':
        //   route.props = ({ params: { depAndMajorMenu } }) => ({
        //     depAndMajorMenu,
        //   });
        //   break;
        case '简历编辑页面':
        case '简历模板':
          route.props = ({
            params: { isEdit, resumeRowInfo, resumeId, companyEmploy },
          }) => ({
            isEdit,
            resumeRowInfo,
            resumeId,
            companyEmploy,
          });
          break;
        case '岗位信息展示':
          route.props = ({ params: { jobForm } }) => ({
            jobForm,
          });
          break;
      }
    }
    // 是否有 独享守卫--前置,
    if (menu.hasBeforeenter) {
      switch (menu.title) {
        case '编辑学员':
        case '新增学生':
          route.beforeEnter = (to, from, next) => {
            //第一个参数to，包含的内容是切换后的路由对象，也就是跳转后的路由对象
            //第二个参数from，包含的内容的是切换前的路由对象，也就是跳转前的路由对象
            //第三个参数next()，是否往下执行，执行的话，如果不写的话路由就不会跳转，操作将会终止
            if (from.path.indexOf(['studentList']) != -1) {
              next();
            } else {
              next({
                name: 'studentList',
              });
            }
          };
          break;
      }
    }
    // 子路由
    if (menu.children && menu.children.length > 0) {
      route.children = convertMenuToRoutes(menu.children);
    }
    routes.push(route);
  });
  return routes;
}

export const loadView = (view) => {
  if (process.env.NODE_ENV === 'development') {
    return (resolve) => require([`@/views/${view}`], resolve);
  } else {
    // 使用 import 实现生产环境的路由懒加载
    return () => import(`@/views/${view}`);
  }
};

export default permission;
